//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.northpool.operator.common.algorithm;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONObject;
import com.northpool.operator.annotation.OperatorInfo;
import com.northpool.operator.common.algorithm.annotation.PluginInfo;
import com.northpool.operator.annotation.InputParam;
import com.northpool.operator.annotation.InputParams;
import com.northpool.operator.utils.ParamUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.Map;

public interface Algorithm {
    default String getName() {
        PluginInfo pluginInfo = AnnotationUtil.getAnnotation(this.getClass(), PluginInfo.class);
        if (pluginInfo == null) {
            OperatorInfo operatorInfo = AnnotationUtil.getAnnotation(this.getClass(), OperatorInfo.class);
            return StringUtils.isNotBlank(operatorInfo.name()) ? operatorInfo.name() : "";
        }
        return pluginInfo.name();
    }

    default String getHint() {
        return "运行算法异常。";
    }

    default void execute(String[] args) throws Exception {
        Map<String, String> envMap = System.getenv();
        // 从stp-job来的请求，环境变量中有建木相关
//        for (String key : envMap.keySet()) {
//            System.out.println(key + " : " + envMap.get(key));
//        }
        this.progress(0);
        if (StringUtils.isNotEmpty(envMap.get("JM_INSTANCE_NAME"))) {
            Map<String, String> params = new LinkedHashMap<>();
            InputParams inputParams = AnnotationUtil.getAnnotation(this.getClass().getConstructors()[0], InputParams.class);
            for (InputParam inputParam : inputParams.value()) {
                String value = ParamUtils.parse(inputParam.ref());
                params.put(inputParam.ref(), value);
            }
            this.execute(params);
        } else {
            this.execute(Helper.xmlArg2Map(args));
        }
        this.progress(100);
    }

    default void execute(Map<String, String> params) throws Exception {
        throw new Exception("抽象错误，execute方法必须实现。");
    }

    default void dispose() {
        this.logMsg("算法执行结束！");
    }

    default void logMsg(String msg) {
        this.logInfo(LocalDateTime.now().toString().replace('T', ' ') + ": " + msg);
    }

    default void logResult(String tag, String msg) {
        // 写入resultFile
        String resultFilePath = System.getenv().get("STP_JOB_RESULT_FILE");
        if (StringUtils.isNotBlank(resultFilePath)) {
            File file = FileUtil.file(resultFilePath);
            try {
                JSONObject jsonObject = new JSONObject();
                if (file.exists()) {
                    String content = FileUtil.readUtf8String(file);
                    jsonObject = JSONObject.parseObject(content);
                }
                jsonObject.put(tag, msg);
                FileUtil.writeUtf8String(jsonObject.toJSONString(), file);
            }catch (Exception ex) {
                logError("结果文件写入失败：" + ex.getMessage());
                failedExit();
            }
        }

        if (tag != null && !tag.isEmpty()) {
            this.logInfo(String.format("<%1$s>%2$s</%1$s>", tag, msg));
        } else {
            this.logResult(msg);
        }
    }

    default void logResult(String msg) {
        this.logResult("result", msg);
    }

    default void logInfo(String msg) {
        System.out.println(msg);
    }

    default void progress(int p) {
        System.out.println("<progress>" + p + "</progress>");
    }

    default void successExit() {
        SystemWrapper.exit(0);
    }

    default void failedExit() {
        SystemWrapper.exit(10);
    }

    default void logError(String msg) {
        this.logInfo("<result><status>1</status><msg>" + msg + "</msg></result>");
    }

    default void logError(int status, String msg) {
        this.logInfo("<result><status>" + status + "</status><msg>" + msg + "</msg></result>");
    }

    default void waiting(int hour) {
        try {
            Thread.sleep((long) hour * 60 * 1000);
        } catch (InterruptedException var3) {
            this.logError("等待异常。");
        }
    }
}
